<template>
    <div>
        <div class="w-form-header" v-if="userStore.userInfo?.authority?.authorityId !== 1000">
            <!-- <span>项目咨询详情</span> -->
            <div>
                <el-button
                    v-if="isEditing"
                    type="primary"
                    @click="isEditing = false"
                    >编辑</el-button
                >
                <el-button
                    v-else
                    type="success"
                    @click="save('1')"
                    :loading="saveLoading"
                    >保存</el-button
                >
            </div>
        </div>
        <div class="gva-form-box admin-content">
            <div class="w-form-box">
                <div class="list-header">基本信息</div>
            </div>
            <el-descriptions class="margin-top" title="" :column="4" border>
                <el-descriptions-item
                    label-class-name="my-label"
                    class-name="my-content"
                >
                    <template #label>
                        <div class="cell-item">项目编号</div>
                    </template>
                    {{ formData.projectNum }}
                </el-descriptions-item>
                <el-descriptions-item
                    label-class-name="my-label"
                    class-name="my-content"
                >
                    <template #label>
                        <div class="cell-item">客户编号</div>
                    </template>
                    <el-select
                        :disabled="isEditing"
                        v-model="formData.customerName"
                        :placeholder="`${il8n('kehubianhao.placeholder')}:`"
                        style="width: 100%"
                        filterable
                        @focus="customerFocur"
                        @change="customerChange"
                    >
                        <el-option
                            v-for="(item, key) in customerOptions"
                            :key="key"
                            :label="item.customerNum"
                            :value="item.customerNum"
                        />
                    </el-select>
                </el-descriptions-item>
                <el-descriptions-item
                    label-class-name="my-label"
                    class-name="my-content"
                >
                    <template #label>
                        <div class="cell-item">创建时间</div>
                    </template>
                    {{ formatDate(formData.CreatedAt, "yyyy-MM-dd hh:mm:ss") }}
                </el-descriptions-item>
                <el-descriptions-item
                    label-class-name="my-label"
                    class-name="my-content"
                >
                    <template #label>
                        <div class="cell-item">创建人</div>
                    </template>
                    <!-- {{ formData.createdUser?.nickName }} -->
                    <span
                        v-if="
                            formData.createdUser &&
                            formData.createdUser.nickName
                        "
                    >
                        {{ formData.createdUser.nickName }}
                    </span>
                    <span v-else>{{ formData.createUser }}</span>
                </el-descriptions-item>
                <el-descriptions-item
                    label-class-name="my-label"
                    class-name="my-content"
                >
                    <template #label>
                        <div class="cell-item">SBU</div>
                    </template>
                    <el-select
                        :disabled="isEditing"
                        v-model="formData.sbuName"
                        placeholder="请选择SBU"
                        style="width: 100%"
                        filterable
                        remote
                        :remote-method="getSbuData"
                        @change="sbuChange"
                    >
                        <el-option
                            v-for="(item, key) in sbuOptions"
                            :key="key"
                            :label="item.sbuName"
                            :value="item.sbuName"
                        />
                    </el-select>
                </el-descriptions-item>
                <el-descriptions-item
                    label-class-name="my-label"
                    class-name="my-content"
                >
                    <template #label>
                        <div class="cell-item">客户品牌</div>
                    </template>
                    <el-select
                        :disabled="isEditing"
                        v-model="formData.brandName"
                        :placeholder="`${il8n('pinpai.placeholder')}:`"
                        style="width: 100%"
                        :clearable="true"
                        filterable
                        @focus="brandFocur"
                    >
                        <el-option
                            v-for="(item, key) in brandOptions"
                            :key="key"
                            :label="item.brandName"
                            :value="item.brandName"
                        />
                    </el-select>
                </el-descriptions-item>
                <el-descriptions-item
                    label-class-name="my-label"
                    class-name="my-content"
                >
                    <template #label>
                        <div class="cell-item">更新时间</div>
                    </template>
                    {{ formatDate(formData.UpdatedAt, "yyyy-MM-dd hh:mm:ss") }}
                </el-descriptions-item>
                <el-descriptions-item
                    label-class-name="my-label"
                    class-name="my-content"
                >
                    <template #label>
                        <div class="cell-item">更新人</div>
                    </template>
                    <!-- {{ formData.updatedUser?.nickName }} -->
                    <span
                        v-if="
                            formData.updatedUser &&
                            formData.updatedUser.nickName
                        "
                    >
                        {{ formData.updatedUser.nickName }}
                    </span>
                    <span v-else>{{ formData.updateUser }}</span>
                </el-descriptions-item>
            </el-descriptions>
        </div>
    </div>
</template>

<script setup>
import {
    createSbuProjects,
    updateSbuProjects,
    findSbuProjects,
} from "@/api/plmSbuProjects";
import { getCustomerInfoList, findCustomerInfo } from "@/api/confCustomerInfo";
import { getSbuDataList, findSbuData } from "@/api/confSbuData";
import { getBrandDataList } from "@/api/confBrandData";
import { getSbuProjectsList } from "@/api/plmSbuProjects";

defineOptions({
    name: "SbuProjectsFormView",
});

// 自动获取字典
import { getDictFunc } from "@/utils/format";
import { emitter } from "@/utils/bus.js";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted } from "vue";
import { useI18n } from "vue-i18n";

const { t: il8n } = useI18n();

// 全量引入格式化工具 请按需保留
import { formatDate } from "@/utils/format";

const route = useRoute();
const router = useRouter();
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()

const type = ref("");
const sbuTypesOptions = ref([]);
const loading = ref(false);
const sbuOptions = ref([]); // sbu列表
const customerOptions = ref([]); // 客户编号列表
const brandOptions = ref([]); // 品牌列表
const saveLoading = ref(false); // 保存状态
const formData = ref({
    sbuName: "",
    customerName: "",
    brandName: "",
});
// 验证规则
const rule = reactive({
    sbuName: [{ required: true, message: "请选择SBU", trigger: "change" }],
    customerName: [
        { required: true, message: "请选择客户编号", trigger: "change" },
    ],
    brandName: [{ required: true, message: "请选择品牌", trigger: "change" }],
});
const projectListOptions = ref([]); // 项目编号列表

const elFormRef = ref();

// 初始化方法
const init = async () => {
    // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.id) {
        const res = await findSbuProjects({ ID: route.query.id });
        if (res.code === 0) {
            formData.value = res.data.resbuProjects;
            findSbuData({ sbuName: formData.value.sbuName }).then((res) => {
                customerOptions.value = res.data.resbuData.customerNum
                    .split(",")
                    .map((res) => {
                        return { customerNum: res };
                    });
            });
            getBrandData(formData.value.customerName);
            type.value = "update";
        }
    } else {
        type.value = "create";
    }
    sbuTypesOptions.value = await getDictFunc("sbuTypes");
};

const isEditing = ref(false);

init();
// 保存按钮
const save = async () => {
    if (!formData.value.customerName) {
        ElMessage({
            type: "warning",
            message: "客户编号不能为空",
        });
        return;
    }
    if (!formData.value.brandName && formData.value.customerName != 'INHSE') {
        ElMessage({
            type: "warning",
            message: "品牌不能为空",
        });
        return;
    }
    saveLoading.value = true;
    await updateSbuProjects(formData.value).then((res) => {
        saveLoading.value = false;
        if (res.code === 0) {
            // init();
            ElMessage({
                type: "success",
                message: "更改成功",
            });
            isEditing.value = true;
        }
    });
};

// 获取sbu列表
const getSbuData = async (keyword) => {
    await getSbuDataList({ page: 1, pageSize: 100, sbuName: keyword }).then(
        (res) => {
            if (res.code === 0) {
                sbuOptions.value = res.data.list;
            }
        }
    );
};

// 获取品牌列表
const getBrandData = async (customerNum) => {
    await findCustomerInfo({ customerNum: customerNum }).then((res) => {
        if (res.code === 0) {
            brandOptions.value = res.data.recustomerInfo.brandDatas;
        }
    });
};

// select的sbu改变sbuChange
const sbuChange = () => {
    let index = sbuOptions.value.findIndex((item) => {
        return item.sbuName == formData.value.sbuName;
    });
    formData.value.customerName = "";
    formData.value.brandName = "";
    customerOptions.value = sbuOptions.value[index].customerNum
        .split(",")
        .map((res) => {
            return { customerNum: res };
        });
    brandOptions.value = [];
};

// select搜索客户编号列表
const customerFocur = async (query) => {
    console.log("搜索", query);
    if (!formData.value.sbuName) {
        ElMessage({
            type: "warning",
            message: "请先选择sbu",
        });
        return;
    }
};
// 客户编号改变
const customerChange = () => {
    let index = customerOptions.value.findIndex((item) => {
        return item.customerNum == formData.value.customerName;
    });
    formData.value.brandName = "";
    // 获取品牌列表
    brandOptions.value = [];
    getBrandData(customerOptions.value[index].customerNum);
};

// 查询项目编号列表
const remoteMethodProject = async (keyword) => {
    const table = await getSbuProjectsList({
        page: 1,
        pageSize: 50,
        projectNum: keyword ? keyword : undefined,
    });
    if (table.code === 0) {
        projectListOptions.value = table.data.list;
    }
};
// select搜索品牌列表
const brandFocur = async (query) => {
    if (!formData.value.customerName) {
        ElMessage({
            type: "warning",
            message: "请先选客户",
        });
        return;
    }
    // console.log("搜索", query);
    // getBrandData(query);
};

onMounted(() => {
    isEditing.value = true;
    getSbuData();
    remoteMethodProject();
});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
.form-box {
    width: 45%;
    margin: 0 auto;
}
.form-footer {
    text-align: center;
}
.gva-form-box {
    :deep(.my-label) {
        width: 9%;
    }
    :deep(.my-content) {
        width: 16%;
    }
}
</style>
